<template>
	<view>
		<u-upload :fileList="picsList" @afterRead="afterRead" @delete="deletePic" multiple :maxCount="limit"></u-upload>
		
	</view>
</template>

<script>
	import { uploadFile } from '@/api/api.js'
	
	export default {
		name:"ImageUpload",
		props: {
			value: [String, Object, Array],
			// 图片数量限制
			limit: {
			  type: Number,
			  default: 5,
			},
			// 大小限制(MB)
			fileSize: {
			  type: Number,
			  default: 5,
			},
			// 文件类型, 例如['png', 'jpg', 'jpeg']
			fileType: {
			  type: Array,
			  default: () => ["png", "jpg", "jpeg"],
			},
			// 是否显示提示
			isShowTip: {
			  type: Boolean,
			  default: true
			}
		 },
		data() {
			return {
				picsList: [],
			};
		},
		watch: {
		    value: {
		      handler(val) {
		        if (val) {
		          // 首先将值转为数组
		          const list = Array.isArray(val) ? val : this.value.split(',');
		          // 然后将数组转为对象数组
		          this.picsList = list.map(item => {
		            if (typeof item === "string") {
		              item = {url: item };
		            }
		            return item;
		          });
		        } else {
		          this.picsList = [];
		          return [];
		        }
		      },
		      deep: true,
		      immediate: true
		    }
		},
		methods: {
			// 删除图片
			deletePic(event) {
				this.picsList.splice(event.index, 1)
				this.$emit("input", this.listToString(this.picsList));
			},
			// 新增图片
			async afterRead(event) {
				//当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.picsList.length
				lists.map((item) => {
					this.picsList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.picsList[fileListLen]
					this.picsList.splice(fileListLen, 1, Object.assign({
						url: result
					}))
					fileListLen++
					this.$emit("input", this.listToString(this.picsList));

				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uploadFile(url).then(res => {
						resolve(res.data.url)
					});
				})
			},
			
			// 对象转成指定字符串分隔
			listToString(list, separator) {
			  let strs = "";
			  separator = separator || ",";
			  for (let i in list) {
				strs += list[i].url + separator;
			  }
			  return strs != '' ? strs.substr(0, strs.length - 1) : '';
			}
		}
	}
</script>

<style>

</style>